/**
 * Description:该类主要用于创建一个标签
 * Copyright: 成都和为科技有限公司 2012
 *
 * 属性：
 *   text - 输入框默认值
 *   placement - 弹出框显示位置 "bottom-left"
 *   format - 格式化, 默认yyyy-mm-dd， 支持yyyy-mm-dd hh:ii, yyyy, yyyy-mm
 */
function DateField() {}

DateField.inherit(Input);

/**
 * 初始化方法
 */
DateField.prototype.init = function () {
	DateField.base.init.call(this);
}

/**
 * 创建HTML节点
 */
DateField.prototype.create = function () {
    this._html = document.createElement("div");
    $(this._html).append("<div class='input-group date form_date' data-date-format='yyyy-mm-dd'>" +
                                "<input class='form-control'/>" +
                                "<span class='input-group-addon'>" +
                                    "<span class='glyphicon glyphicon-calendar' style='cursor:pointer'></span>" +
                                "</span>" +
                           "</div>");
}

DateField.prototype.initLoad = function() {
    DateField.base.initLoad.call(this);
    if (!$().datetimepicker) {
        this.loadScriptFile("/webapi/common/datetimepicker/bootstrap-datetimepicker.js");
        this.loadScriptFile("/webapi/common/datetimepicker/bootstrap-datetimepicker.zh-CN.js");
        this.loadCSSFile("/webapi/common/datetimepicker/bootstrap-datetimepicker.css");
    }
    var oInput = $("input",this._html);
    if (this._attr.describle) {
        oInput.attr("placeholder", this._attr.describle);
    }
    if (this._attr.text) {
        oInput[0].value = this._attr.text;
    }
    if (this._attr.disabled == "true") {
        this.setDisable();
    }
    var othis = this;
    oInput.bind("focus", function(e){
        othis.focus(e);
    });
    oInput.bind("blur", function(e){
        othis.blur(e);
    });
    this.datepicker = false;
    $(this._html).bind("click", function(e){
        othis.loadDateControl(e);
    });
}

DateField.prototype.loadDateControl = function() {
	var minView = 2;
    var startView = 2;
    if (this._attr.format) {
        var sFormat = this._attr.format;
        $('.date', this.getHTML()).data("date-format", sFormat);
        if (sFormat == "yyyy-mm-dd hh:ii")  minView = 0;
        if (sFormat == "yyyy-mm")  {
            startView = 3;
            minView = 3;
        }
        if (sFormat == "yyyy")  {
            startView = 4;
            minView = 4;
        }
    }
    var placement = "bottom-left";
    if (this._attr.placement) {
        placement = this._attr.placement;
    }
    
	if (!this.datepicker) {
	    $('.form_date', this.getHTML()).datetimepicker({
	        language:  'zh-CN',
	        weekStart: 1,
	        todayBtn:  1,
	        autoclose: 1,
	        todayHighlight: 1,
	        startView: startView,
	        minView: minView,
	        pickerPosition:placement,
	        forceParse: 0
	    });
	    //改变值调用事件
	    var othis = this;
	    $('.form_date', this.getHTML()).datetimepicker().on('changeDate', function(ev) {
	        var event = new Object();
	        event.currentTarget = $("input", othis.getHTML())[0];
	        othis.setValidate(true);
	        othis.blur(event);
	    });
	    $("input", this.getHTML()).focus();
	    this.datepicker = true;
	}
}

/**
 * 手动输入日期认证
 */
DateField.prototype.validateControl = function(sValue) {
    if (sValue == "") return true;
    var sFormat = "yyyy-mm-dd";
    if (this._attr.format) {
        sFormat = this._attr.format;
    }
    var succcess = true;
    if (sFormat == "yyyy-mm-dd hh:ii") {
        var reg = /^([1-2]\d{3})[\/|\-](0?[1-9]|10|11|12)[\/|\-]([1-2]?[0-9]|0[1-9]|30|31) ([0-1]?[0-9]|2[0-3]):([0-5]?[0-9])$/;
        if (sValue.match(reg) == null) {
            succcess = false;
        }
    } else if (sFormat == "yyyy-mm-dd"){
        return this.validateDate(sValue);
    } else if (sFormat == "yyyy-mm"){
        var reg =  /^([1-2]\d{3})[\/|\-](0?[1-9]|10|11|12)$/;
        if (sValue.match(reg) == null) {
            succcess = false;
        }
    } else if (sFormat == "yyyy") {
        var reg =  /^([1-2]\d{3})$/;
        if (sValue.match(reg) == null) {
            succcess = false;
        }
    }
    if (!succcess) this.setValidate(false,"请录入正确格式(" + sFormat + ")!");
    return succcess;
}

DateField.prototype.validateDate = function(sValue) {
    var oInput = $("input",this.getHTML())[0];
    var sInput = oInput.value.trim();
    if(sInput == "") return true;
    if (0 == sInput.search(/^[jJ]|[zZ]|[qQ]|[mM]|[hM]|[-+]?\d{1,4}$/)) {//如果使用了快捷输入方式
        var iOffset = 0;

        if (0 == sInput.search(/^[-+]?\d+$/)) {
            iOffset = sInput;
        }
        else {
            switch (sInput.toUpperCase()) {
                case "J":
                    iOffset = 0;
                    break;
                case "Z":
                    iOffset = -1;
                    break;
                case "Q":
                    iOffset = -2;
                    break;
                case "M":
                    iOffset = 1;
                    break;
                case "H":
                    iOffset = 2;
                    break;
                default:
            }
        }
        if (iOffset < -9999 || iOffset > 9999) {
            return false;
        }
        var today = new Date();
        var need_date = new Date(today.getTime() + iOffset * 1000 * 3600 * 24);

        if (need_date.getFullYear() < 1800 || need_date.getYear() > 2099) {
            return false;
        }
        var s_year = need_date.getFullYear().toString();

        var s_month = (need_date.getMonth() + 1).toString();
        if (0 <= need_date.getMonth() &&  need_date.getMonth() <= 8) {
            s_month = "0" + s_month;
        }

        var s_date = need_date.getDate().toString();
        if (1 <= need_date.getDate() && need_date.getDate() <= 9) {
            s_date = "0" + s_date;
        }

        oInput.value = s_year + "-" + s_month + "-" + s_date;
        $('.form_date', this.getHTML()).datetimepicker('update');
        return true;
    }

    re = /^(\d{4})(-|\/)?(\d{1,2})\2(\d{1,2})$/;
    if (sInput.match(re) != null) {
        var tmpDate = new Date(RegExp.$1,RegExp.$3-1,RegExp.$4);
        var year = tmpDate.getYear();
        //fixed 19xx problem
        if (year<1900)
            year += 1900;
        if (year>=1900 && year == RegExp.$1 &&
            tmpDate.getMonth()+1 == RegExp.$3 &&
            tmpDate.getDate() == RegExp.$4 )
        {
            var tempmonth = RegExp.$3;
            var tempday = RegExp.$4;
            //if(RegExp.$2 != null && RegExp.$2 != ""){
            if(RegExp.$3.length == 1){
                tempmonth = "0" + tempmonth;
            }
            if(RegExp.$4.length == 1){
                tempday = "0" + tempday;
            }
            //}
            oInput.value=RegExp.$1+"-"+tempmonth+"-"+tempday;
            $('.form_date', this.getHTML()).datetimepicker('update');
            return true;
        }else{
        	 //测试说提示信息不人性化
        	 this.setValidate(false);
    		 this.setError("不能输入年份小于1900的日期!");
    		 return false;
        }
    }
    this.setValidate(false);
    this.setError("请录入正确格式(YYYY-MM-DD)!");
    return false;
}

/**
 * 获取当前控件的值。需要提交到数据库
 */
DateField.prototype.getValue = function(){
	if(!this.isValidate() ){
		return "";
	}else{
        //兼容IE8，placeholder会被搞成value
        if($("input",this._html)[0].value==$("input",this._html)[0].placeholder){
            return "";
        }else{
            return $("input",this._html)[0].value;
        }
	}
}

/**
 * 赋予当前控件的值。
 */
DateField.prototype.setValue = function(value) {
    DateField.base.setValue.call(this);
	$("input",this._html)[0].value = value;
}

/**
 * 设置为可编辑
 */
DateField.prototype.setEnable = function(){
	DateField.base.setEnable.call(this);
	$("input",this._html)[0].disabled = false;
	$(".input-group-addon",this._html).show();
	var othis = this;
	$(this._html).bind("click", function(e){
        othis.loadDateControl(e);
    });
}

/**
 * 设置为只读
 */
DateField.prototype.setDisable = function(){
	DateField.base.setDisable.call(this);
	$("input",this._html).attr("disabled","true");
	$(".input-group-addon",this._html).hide();
	$(this._html).unbind("click");
}


